
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生信息</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search">
      <label>学号:<input type="text" placeholder="请输入学号" v-model="studentID"/></label>
      <label>姓名:<input type="text" placeholder="请输入姓名" v-model="name"/></label>
    </div>
    <el-table :data="tableData" :height="height">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="学号">
              <span>{{ scope.row.studentId }}</span>
            </el-form-item>
            <el-form-item label="姓名">
              <span>{{ scope.row.name }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ scope.row.sex }}</span>
            </el-form-item>
            <el-form-item label="年龄">
              <span>{{ scope.row.age }}</span>
            </el-form-item>
            <el-form-item label="班级">
              <span>{{ scope.row.classId }}</span>
            </el-form-item>
            <el-form-item label="学院">
              <span>{{ scope.row.collegeId }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="学号" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.studentId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级" width="240">
        <template slot-scope="scope">
          <span>{{ scope.row.classId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :page-sizes="[1, 2, 3]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
    <!-- 编辑表单弹窗 -->
    <el-dialog
      title="编辑学生信息"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="formLabelWidth">
  <el-form-item label="学籍编号" prop="studentId">
    <el-input v-model="ruleForm.studentId" :disabled="true"></el-input>
  </el-form-item>
  <el-form-item label="学生姓名" prop="name">
    <el-input v-model="ruleForm.name"></el-input>
  </el-form-item>
  <el-form-item label="学生性别" prop="sex">
    <el-radio-group v-model="ruleForm.sex">
      <el-radio label="男">男</el-radio>
      <el-radio label="女">女</el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="学生年龄" prop="age">
    <el-input v-model.number="ruleForm.age"></el-input>
  </el-form-item>
  <el-form-item label="学生班级" prop="classId">
    <el-input v-model="ruleForm.classId"></el-input>
  </el-form-item>
  <el-form-item label="学生学院" prop="collegeId">
    <el-input v-model="ruleForm.collegeId"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="ruleForm.password"></el-input>
  </el-form-item>
</el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="updateEdit(ruleForm)">确定</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
export default {
  name: "StudentInfo",
  data() {
    return {
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
      title: "学生信息表",
      tableData: [],
      height: document.documentElement.clientHeight - 120,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      pageFrom:{
        page: 1,
        pageSize: 3,
      },
      studentID:'',
        name:'',
        // 修改数据的表单
      ruleForm: {studentId:'',sex:'',name:'',age:'',collegeId:'',classId:'',password:''},
      rules: {
        name: [{ required: true, message: "请填写学生姓名" }],
        sex: [{ required: true, message: "请选择学生性别" }],
        age: [{ required: true, message: "请填写学生年龄" }],
        classId: [{ required: true, message: "请填写学生班级" }],
      },
    };
  },
  created(){
    if(localStorage.getItem("type") !== 'admin'){this.$router.push(`/login`);this.$message.error('权限不够');}
  },
  methods: {
    // 数据分页
    handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
      this.getStudentTable()
    },
    handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      this.getStudentTable()
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
    },
    // 获取学生信息表
    async getStudentTable() {
      const dataToSerialize = { ...this.pageFrom };
      if (this.studentID) {
    dataToSerialize.studentId=this.studentID;
}

     if (this.name) {
    dataToSerialize.name=this.name;
}
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json', // Custom request header
        'token':`${localStorage.getItem("token")}`
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/student/page`,JSON.stringify(dataToSerialize),config);
      if (res.status !== 500) {
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    
    },
    // 获取学生初始数据
    async getFirstStudentTable() {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json', // Custom request header
        'token':`${localStorage.getItem("token")}`
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/student/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.$message.success('成功获取学生成绩');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    
    },
    //删除学生信息
    async deleteStudentInfo(ID) {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded', // Custom request header
        'token':`${localStorage.getItem("token")}`
      }
    };
    try {
      const { data: res } = await this.$http.delete(`api/admin/student/delete?id=${ID}`,config);
      if (res.status !== 500) {
        this.$message.success('成功删除学生信息');
        // 重新调用获取表格的代码
        this.getFirstStudentTable();
      } else {
        this.$message.error('删除失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('删除失败');
  }
    },
    // 启动编辑功能
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.ruleForm = { ...row };

    },
    // 保存编辑按钮
    async updateEdit(params) {
      if (confirm("是否确认所编辑的内容！")){
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json', // Custom request header
        'token':`${localStorage.getItem("token")}`
      }
    };
    try {
      const { data: res } = await this.$http.put(`api/admin/student/update`,JSON.stringify(params),config);
      if (res.status !== 500) {
        this.$message.success('成功编辑学生信息');
        // 重新调用获取表格的代码
        this.getStudentTable();
        this.dialogFormVisible = false;
      } else {
        this.$message.error('编辑失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('编辑失败');
  }
}
},
    // 取消编辑按钮
    cancelEdit() {
      if (confirm("是否确认取消所编辑的内容！")) {
        this.dialogFormVisible = false;
      }
    },
    // 删除功能
    handleDelete(index, row) {
      if (confirm("是否确认删除？")) {
        this.deleteStudentInfo(row.studentId);
      }
    },
  },

  mounted() {
    this.getFirstStudentTable();
  },
};
</script>

<style lang="less" scoped>
.search {
  background-color: #fff;
  padding:10px 5px;
  font-size:14px;
  text-align: right;
}
.search label {
  margin-right:30px;
}
.search input {
  margin-left:10px;
  width:160px;
  outline: none;
}
.el-breadcrumb {
  padding-bottom: 10px;
}
.el-table {
  width: 100%;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-left: 70px;
  margin-bottom: 0;
  min-width: 40%;
  max-width: 84%;
}
/deep/ .el-table .el-table__cell {
  padding: 8px 0;
}
/deep/ .el-dialog {
  margin-top: 10px !important;
}
/deep/.el-dialog__body {
  padding: 10px 20px !important;
  font-size: 12px !important;
}
/deep/.el-dialog__footer {
  padding: 0px 20px 10px !important;
}
</style>
